#!/usr/bin/env bash
# Configure ssh host keys if they exists in mdata

. /lib/svc/share/smf_include.sh

# Set basedir and default config file
SSH_HOSTS='/var/ssh'

# Do nothing if not under SMF
if [[ ! "${SMF_METHOD}" == "start" ]]; then
	exit ${SMF_EXIT_OK}
fi

# Update mdata information from SSH host keys
for key in dsa_key dsa_key.pub rsa_key rsa_key.pub ecdsa_key ecdsa_key.pub ed25519_key ed25519_key.pub; do
	# If mdata is set we update the host keys, else we will get the
	# host keys from the filesystem and set the mdata information
	if mdata-get ssh_host_${key} 2>/dev/null; then
		mdata-get ssh_host_${key} > ${SSH_HOSTS}/ssh_host_${key}
	else
		cat ${SSH_HOSTS}/ssh_host_${key} |\
			mdata-put ssh_host_${key}
	fi
done

# Disable service after run once
svcadm disable svc:/network/ssh-hostkey-mdata-setup

exit ${SMF_EXIT_OK}
